package com.rpa.server.servicerpaserver.crawler.operate;

import cn.hutool.core.map.MapUtil;
import com.google.common.annotations.VisibleForTesting;
import com.rpa.secure.servicerpasecure.common.constant.JumpJudgmentConstant;
import com.rpa.secure.servicerpasecure.common.constant.MessageConstant;
import com.rpa.secure.servicerpasecure.common.constant.UrlConstant;
import com.rpa.secure.servicerpasecure.common.exception.TaskException;
import com.rpa.server.servicerpaserver.crawler.entity.User;
import com.rpa.server.servicerpaserver.crawler.service.UserService;
import com.rpa.server.servicerpaserver.crawler.service.impl.UerServiceImpl;
import com.rpa.server.servicerpaserver.util.CookieSerialize;
import com.rpa.server.servicerpaserver.util.WebDriverUtil;
import io.github.bonigarcia.wdm.WebDriverManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.exec.util.MapUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;

/**
 * @className: LogonOperate
 * @author: lzt
 * @date: 2025/1/9 15:04
 * @Version: 1.0
 * @description:
 */
@Component
@Slf4j
@DependsOn("uerServiceImpl")
public class LogonOperate {
    @Autowired
    private CookieSerialize cookieSerialize;
    private final UserService userService;

    @Autowired
    public LogonOperate(UserService uerService) {
        this.userService = uerService;
    }

    @Async("logonTaskExecutor")
    public CompletableFuture<Boolean> logonCX(Long rpaRegisterId) {
        User user = userService.getById(rpaRegisterId);
        if (user == null) {
            throw new TaskException(MessageConstant.NO_USER);
        }
        ChromeOptions options = new ChromeOptions();
        WebDriverUtil.setupWebDriver(options);
        ChromeDriver chromeDriver = null;
        String xingAccount = user.getXingAccount();
        String xingPassword = user.getXingPassword();
        String id = user.getId().toString();
        try {
            chromeDriver = new ChromeDriver(options);
            chromeDriver.get(UrlConstant.PASSPORT_CHAOXING);
            WebDriverWait wait = new WebDriverWait(chromeDriver, Duration.ofSeconds(5)); // 增加等待时间
            wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id='phone']")));
            WebElement phoneElement = chromeDriver.findElement(By.xpath("//*[@id=\"phone\"]"));
            phoneElement.sendKeys(xingAccount);
            WebElement pwd = chromeDriver.findElement(By.xpath("//*[@id=\"pwd\"]"));
            pwd.sendKeys(xingPassword);
            WebElement loginBtn = chromeDriver.findElement(By.xpath("//*[@id=\"loginBtn\"]"));
            loginBtn.click();
            if (wait.until(ExpectedConditions.titleIs(JumpJudgmentConstant.REGISTER_INDEX_CHAOXING))) {
                Set<Cookie> cookies = chromeDriver.manage().getCookies();
                cookieSerialize.saveCookies(user.getId().toString(), cookies);
                cookieSerialize.saveCookies(user.getId().toString() + "WORK", cookies);
                cookieSerialize.saveCookies(user.getId().toString() + "ACTIVE", cookies);
                log.info("登录成功，账号为: {}，存入主键为:{}", xingAccount, id);
                return CompletableFuture.completedFuture(true);
            } else {
                log.error("登录失败，账号为: {}，存入主键为:{}", xingAccount, id);
                return CompletableFuture.completedFuture(false);
            }
        } catch (Exception e) {
            log.error("登录失败，账号为: {}，存入主键为:{},异常信息为:{}", xingAccount, id, e);
            return CompletableFuture.completedFuture(false);
        } finally {
            WebDriverUtil.closeWebDriver(chromeDriver);
        }
    }

    @Async("logonTaskExecutor")
    public CompletableFuture<Boolean> logonStu(String rpaRegisterId) {
        User user = userService.getById(rpaRegisterId);
        if (user == null) {
            throw new TaskException(MessageConstant.NO_USER);
        }
        WebDriverManager.chromedriver().setup();
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--disable-gpu");
        options.addArguments("--remote-allow-origins=*");
        options.addArguments("--start-maximized");
        WebDriver chromeDriver = new ChromeDriver(options);

        String stuAccount = user.getStuAccount();
        String stuPassword = user.getStuPassword();

        String id = user.getId().toString();
        try {

            chromeDriver.get(UrlConstant.PASSPORT_EDUCATIONAL);
            WebDriverWait wait = new WebDriverWait(chromeDriver, Duration.ofSeconds(60));

            wait.until(d -> d.getCurrentUrl().startsWith("https://jwgl.baiyunu.edu.cn/"));
            System.out.println("登录页面加载完成");
            String currentUrl = chromeDriver.getCurrentUrl();
            System.out.println("当前URL：" + currentUrl);
            WebElement iframe = chromeDriver.findElement(By.id("frm_login"));
            chromeDriver.switchTo().frame(iframe);

            // 选择用户类型
            WebElement selectElement = chromeDriver.findElement(By.xpath("//select[@name='Sel_Type']"));
            Select userTypeSelect = new Select(selectElement);
            userTypeSelect.selectByValue("TEA");

            // 输入账号
            WebElement accountElement = chromeDriver.findElement(By.id("txt_asmcdefsddsd"));
            accountElement.clear();
            accountElement.sendKeys(stuAccount);

            // 输入密码
            JavascriptExecutor js = (JavascriptExecutor) chromeDriver;
            js.executeScript("document.getElementById('txt_pewerwedsdfsdff').style.display='block';");
            WebElement password = wait.until(ExpectedConditions.elementToBeClickable(By.id("txt_pewerwedsdfsdff")));
            password.clear();
            password.sendKeys(stuPassword);
            WebElement logBut = chromeDriver.findElement(By.xpath("//*[@id=\"btn_login\"]"));
            logBut.click();
            if (wait.until(ExpectedConditions.titleIs(JumpJudgmentConstant.REGISTER_INDEX_STU))) {
                Set<Cookie> cookies = chromeDriver.manage().getCookies();
                cookieSerialize.saveCookies(user.getId().toString() + "STU", cookies);
                log.info("登录成功，账号为: {}，存入主键为:{}", stuAccount, id);
                return CompletableFuture.completedFuture(true);
            } else {
                log.error("登录失败，账号为: {}，存入主键为:{}", stuAccount, id);
                return CompletableFuture.completedFuture(false);
            }
        } catch (Exception e) {
            log.error("登录失败，账号为: {}，存入主键为:{},异常信息为:{}", stuAccount, id, e);
            return CompletableFuture.completedFuture(false);
        }
    }




    /*public static void main(String[] args) {
        WebDriverManager.chromedriver().setup();
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--disable-gpu");
        options.addArguments("--remote-allow-origins=*");
        options.addArguments("--start-maximized");

        String xingAccount = "202202181";
        String xingPassword = "cx324105";

        WebDriver chromeDriver = new ChromeDriver(options);

        chromeDriver.get("https://jwgl.baiyunu.edu.cn");

        WebDriverWait wait = new WebDriverWait(chromeDriver, Duration.ofSeconds(60));

        wait.until(d -> d.getCurrentUrl().startsWith("https://jwgl.baiyunu.edu.cn/"));
        System.out.println("登录页面加载完成");
        String currentUrl = chromeDriver.getCurrentUrl();
        System.out.println("当前URL：" + currentUrl);

        try {
            WebElement iframe = chromeDriver.findElement(By.id("frm_login"));
            chromeDriver.switchTo().frame(iframe);

            // 选择用户类型
            WebElement selectElement = chromeDriver.findElement(By.xpath("//select[@name='Sel_Type']"));
            Select userTypeSelect = new Select(selectElement);
            userTypeSelect.selectByValue("TEA");

            // 输入账号
            WebElement accountElement = chromeDriver.findElement(By.id("txt_asmcdefsddsd"));
            accountElement.clear();
            accountElement.sendKeys(xingAccount);

            // 输入密码
            JavascriptExecutor js = (JavascriptExecutor) chromeDriver;
            js.executeScript("document.getElementById('txt_pewerwedsdfsdff').style.display='block';");
            WebElement password = wait.until(ExpectedConditions.elementToBeClickable(By.id("txt_pewerwedsdfsdff")));
            password.clear();
            password.sendKeys(xingPassword);
            WebElement logBut = chromeDriver.findElement(By.xpath("//*[@id=\"btn_login\"]"));
            logBut.click();


            // 点击登录按钮
            WebElement loginBtn = chromeDriver.findElement(By.id("btn_login"));
            loginBtn.click();
        } catch (TimeoutException e) {
            System.out.println("等待登录元素超时，检查页面是否正确加载或元素ID是否正确");
        } catch (NoSuchElementException e) {
            System.out.println("找不到页面元素，检查元素ID是否正确");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/


}
